﻿using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Source.Workflows
{
    /// <summary>
    /// For use in a Dialog when using a Prompt/Response to capture a Two Options response (Yes/No) 
    /// with the intention of directly updating a CRM Two Options field with the response.
    /// 
    /// Default response does not allow setting directly into a Two Options field.
    /// This accepts a string input (response value or text) and converts it into a bool value.
    /// </summary>
    public class ConvertToBool : CodeActivity
    {
        // Input value as a string ("1", "true", "Yes", etc)
        [Input("Bool Value")]
        public InArgument<string> Value { get; set; }

        // The bool value of the input string
        [Output("Result")]
        public OutArgument<bool> Result { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            bool result = false;

            // Get the input string value
            string input = Value.Get<string>(context);
            if (!string.IsNullOrWhiteSpace(input))
            {
                // Check if it's a true value, ignoring case (1, true, or yes), anything else will be false
                string[] trueValues = { "1", "true", "yes" };
                result = trueValues.Contains(input.ToLower());
            }

            // Pass the bool result back to the workflow for processing
            this.Result.Set(context, result);
        }
    }
}
